package com.ccp.dev.workflow.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.workflow.dao.ReferActDefModelDao;
import com.ccp.dev.workflow.model.ReferActDefModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassDescribe:流程定义引用 Service类
 * @author :fanruiqi
 * Date: 2019-08-01
 */
@Service
public class ReferActDefModelService extends BaseService<ReferActDefModel> {
    @Resource
    private ReferActDefModelDao referActDefModelDao;

    /**
     * 查询流程定义引用
     * @param modelId 模型id
     * @return list
     */
    public List<ReferActDefModel> queryByModelId(String modelId) {
        return referActDefModelDao.queryByModelId(modelId);
    }

    /**
     * 更新流程引用
     * 2019-11-12新增，将controller中的方法提取到service中
     * @param modelId 模型id
     * @param delRefers 需要删除的流程引用
     * @param referArr 需要新增的流程引用
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRefers(String modelId,String[] delRefers,String[] referArr){
        //查询已保存的流程引用
        List<ReferActDefModel> oldList = queryByModelId(modelId);
        //删除被取消勾选的流程引用
        if(oldList.size()>0 && delRefers!=null  ){
            for(ReferActDefModel delRefer : oldList ){
                for(String name : delRefers) {
                    if(delRefer.getName().equals(name)) {
                        this.delById(delRefer.getId());
                    }
                }
            }
        }
        //保存流程定义引用
        if (referArr != null) {
            for (String key : referArr) {
                if (StringUtils.isNotBlank(key)) {
                    ReferActDefModel ref = new ReferActDefModel();
                    ref.setId(UUIDUtils.getUUIDFor32());
                    ref.setModelId(modelId);
                    ref.setReferModelKey(key);
                    ref.setState(StringPool.ONE);
                    ref.setRemark("流程定义引用");
                    this.add(ref);
                }
            }
        }
    }
}
